package com.cn.shuangzi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.shuangzi.R;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.cn.shuangzi.view.AlertWidget;


/**
 * Created by CN on 2017-11-28.
 */

public abstract class SZSplashActivity extends SZBaseActivity {
    protected FrameLayout splash_container;
    protected TextView txtSkip;
    protected TextView txtVipSkip;
    protected RelativeLayout rltSplashBg;
    protected RelativeLayout rltBottom;
    protected RelativeLayout rltSelfSplash;
    protected ImageView imgSelfSplash;
    protected TextView txtSelfSplashGo;
    protected ImageView imgApp;
    protected TextView txtAppName;
    protected Handler handlerCtrl;
    protected boolean isToMain;
    protected boolean canJump;
    protected boolean isGoToMainEnd;//是否已经执行打开首页的方法，避免重复打开多个首页
    public static void startOnce(Activity from, Class to) {
        Intent intent = new Intent(from, to);
        Bundle data = new Bundle();
        data.putBoolean("isToMain", false);
        intent.putExtras(data);
        from.startActivity(intent);
        from.overridePendingTransition(0, 0);
    }

    @Override
    public void preLoadChildView() {
        if(isTransparentStatus()) {
            setStatusBarTrans();
        }
    }

    @Override
    protected int onGetChildView() {
        return R.layout.activity_sz_splash;
    }

    @Override
    protected void onBindChildViews() {
        rltSplashBg = findViewById(R.id.rltSplashBg);
        splash_container = findViewById(R.id.splash_container);
        rltBottom = findViewById(R.id.rltBottom);
        imgApp = findViewById(R.id.imgApp);
        txtAppName = findViewById(R.id.txtAppName);
        txtSkip = findViewById(R.id.txtSkip);
        txtVipSkip = findViewById(R.id.txtVipSkip);

        rltSelfSplash = findViewById(R.id.rltSelfSplash);
        imgSelfSplash = findViewById(R.id.imgSelfSplash);
        txtSelfSplashGo = findViewById(R.id.txtSelfSplashGo);

    }

    @Override
    protected void onBindChildListeners() {
    }

    @Override
    protected void onChildViewCreated() {
        // 解决初次安装后打开后按home返回后重新打开重启问题。。。
        if (!this.isTaskRoot()) { //判断该Activity是不是任务空间的源Activity，“非”也就是说是被系统重新实例化出来
            //如果你就放在launcher Activity中话，这里可以直接return了
            Intent mainIntent = getIntent();
            String action = mainIntent.getAction();
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
                SZUtil.log("===系统重新实例化闪屏页===");
                finish();
                overridePendingTransition(0, 0);
                return;//finish()之后该活动会继续执行后面的代码，你可以logCat验证，加return避免可能的exception
            }
        }
        isGoToMainEnd = false;
        isToMain = getIntent().getBooleanExtra("isToMain", true);
        handlerCtrl = new Handler();
        if(isTransparentStatus()){
            findViewById(R.id.viewSpaceSplash).setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,getStatusBarHeight()));
        }
        initSplashInfo();
        hideNavigationBar();
        onPreCreated();
        onCreated();
    }

    @Override
    protected void onReloadData(boolean isRefresh) {

    }

    public void initSplashInfo() {
        if (getSplashRes() != 0) {
            rltSplashBg.setBackgroundResource(getSplashRes());
        }
        if (getAppIconRes() != 0) {
            imgApp.setImageResource(getAppIconRes());
        }
        if (getAppNameRes() != 0) {
            txtAppName.setText(getAppNameRes());
        }
        if (getAppNameColorRes() != 0) {
            txtAppName.setTextColor(getResources().getColor(getAppNameColorRes()));
        }
    }

    public void next() {
        if (canJump) {
            toMain(0);
        } else {
            canJump = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        next();
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    public void toMain(long delay) {
        if (delay == 0||handlerCtrl == null) {
            toMain();
            return;
        }
        handlerCtrl.postDelayed(new Runnable() {
            @Override
            public void run() {
                toMain();
            }
        }, delay);
    }

    public void toMain() {
        if(isGoToMainEnd){
            return;
        }
        isGoToMainEnd = true;
        if(SZUtil.isShowPermissionWithFirstUse(false)) {
            SZUtil.setRequestPermissionInSplashDone();
            SZUtil.setTimeOnRequestPermission();
        }
        if (!isToMain) {
            finish();
            overridePendingTransition(0, 0);
        } else {
            if (!SZApp.getInstance().isAliveActivity(getHomeActivity())) {
                Intent intent = new Intent(this, getHomeActivity());
                startActivity(intent);
            }
            finish();
        }
    }

    public void showDisagreeAlert() {
        final SZXmlUtil xmlUtil = new SZXmlUtil(this, "privacy_alert");
        final AlertWidget alertWidget = new AlertWidget(this);
        alertWidget.show(R.layout.item_privacy_alert);
        alertWidget.setCancelable(false);
        TextView txtPrivacyTitle = alertWidget.getWindow().findViewById(R.id.txtPrivacyTitle);
        TextView txtPrivacyDesc = alertWidget.getWindow().findViewById(R.id.txtPrivacyDesc);
        TextView txtClose = alertWidget.getWindow().findViewById(R.id.txtClose);
        TextView txtAgree = alertWidget.getWindow().findViewById(R.id.txtAgree);
        txtPrivacyTitle.setText("温馨提示");
        txtClose.setText("放弃使用");
        txtClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertWidget.close();
                finish();
            }
        });
        txtAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xmlUtil.put("is_privacy_alert", true);
                alertWidget.close();
                onClickAgreeUse(true);
            }
        });
        String txtUserServiceAgreement = getString(R.string.service_agreement_symbol);
        String txtPrivacyPolicy = getString(R.string.privacy_policy_symbol);
        String desc = getString(R.string.privacy_disagree_content, txtUserServiceAgreement, txtPrivacyPolicy);
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(desc);
        AgreementTextViewSpan agreementTextViewSpan = new AgreementTextViewSpan();
        stringBuilder.setSpan(agreementTextViewSpan, desc.indexOf(txtUserServiceAgreement), desc.indexOf(txtUserServiceAgreement) + txtUserServiceAgreement.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        PolicyTextViewSpan policyTextViewSpan = new PolicyTextViewSpan();
        stringBuilder.setSpan(policyTextViewSpan, desc.indexOf(txtPrivacyPolicy), desc.indexOf(txtPrivacyPolicy) + txtPrivacyPolicy.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        txtPrivacyDesc.setText(stringBuilder);
        txtPrivacyDesc.setHighlightColor(getResources().getColor(android.R.color.transparent));
        txtPrivacyDesc.setMovementMethod(LinkMovementMethod.getInstance());
    }

    public void showServiceAlert() {
        showServiceAlert(null, null, null, null);
    }

    public void showServiceAlert(String title, String desc, String txtUserServiceAgreement, String txtPrivacyPolicy) {
        final SZXmlUtil xmlUtil = new SZXmlUtil(this, "privacy_alert");
        if (!xmlUtil.getBoolean("is_privacy_alert")) {
            final AlertWidget alertWidget = new AlertWidget(this);
            alertWidget.show(R.layout.item_privacy_alert);
            alertWidget.setCancelable(false);
            TextView txtPrivacyTitle = alertWidget.getWindow().findViewById(R.id.txtPrivacyTitle);
            TextView txtPrivacyDesc = alertWidget.getWindow().findViewById(R.id.txtPrivacyDesc);
            TextView txtClose = alertWidget.getWindow().findViewById(R.id.txtClose);
            TextView txtAgree = alertWidget.getWindow().findViewById(R.id.txtAgree);
            txtClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertWidget.close();
                    showDisagreeAlert();
                }
            });
            txtAgree.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    xmlUtil.put("is_privacy_alert", true);
                    alertWidget.close();
                    onClickAgreeUse(true);
                }
            });
            if (title != null) {
                txtPrivacyTitle.setText(title);
            }
            if (txtUserServiceAgreement == null) {
                txtUserServiceAgreement = getString(R.string.service_agreement_symbol);
            }
            if (txtPrivacyPolicy == null) {
                txtPrivacyPolicy = getString(R.string.privacy_policy_symbol);
            }
            if (desc == null) {
                desc = getString(R.string.privacy_content_common, getString(getAppNameRes()), txtUserServiceAgreement, txtPrivacyPolicy);
            }
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder(desc);
            AgreementTextViewSpan agreementTextViewSpan = new AgreementTextViewSpan();
            stringBuilder.setSpan(agreementTextViewSpan, desc.indexOf(txtUserServiceAgreement), desc.indexOf(txtUserServiceAgreement) + txtUserServiceAgreement.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            PolicyTextViewSpan policyTextViewSpan = new PolicyTextViewSpan();
            stringBuilder.setSpan(policyTextViewSpan, desc.indexOf(txtPrivacyPolicy), desc.indexOf(txtPrivacyPolicy) + txtPrivacyPolicy.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            txtPrivacyDesc.setText(stringBuilder);
            txtPrivacyDesc.setHighlightColor(getResources().getColor(android.R.color.transparent));
            txtPrivacyDesc.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            onClickAgreeUse(false);
        }

    }
    private class AgreementTextViewSpan extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(R.color.colorPrimary));
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
            onClickUserServiceAgreement();
        }
    }

    private class PolicyTextViewSpan extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(R.color.colorPrimary));
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View widget) {
            onClickPrivacyPolicy();
        }
    }

    @Override
    public boolean isShowTitleInit() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handlerCtrl != null) {
            handlerCtrl.removeCallbacksAndMessages(null);
        }
        handlerCtrl = null;
    }

    public abstract void onPreCreated();

    public abstract void onCreated();

    public abstract int getSplashRes();

    public abstract int getAppIconRes();

    public abstract int getAppNameRes();

    public abstract int getAppNameColorRes();

    public abstract Class getHomeActivity();

    public abstract void onClickUserServiceAgreement();

    public abstract void onClickPrivacyPolicy();

    public abstract void onClickAgreeUse(boolean isFirstUse);

    public boolean isTransparentStatus(){
        return true;
    }
}
